package cn.cms.controller;

import cn.cms.util.Md5Util;
import cn.cms.util.Util;
import cn.cms.constants.Constants;
import org.perf4j.aop.Profiled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("msg")
@Controller
public class PushMsgController {

    private final static Logger logger = LoggerFactory.getLogger(PushMsgController.class);

//    @Autowired
//    private KafkaTemplate<Integer, String> kafkaTemplate;


    /**
     * 发送消息给KAFKA
     * 签名方法:
     *      将参数id:198737 timestamp:1490067632 ip:1073136168 秘钥:!QAZ#WSX,链接做MD5;
     *      如:MD5("19873714900676321073136168!QAZ#WSX")
     * 测试地址:http://10.154.30.30:8098
     * 正式地址:http://10.150.140.83
     * uri:/msg/push/198737/1490067632/1073136168/535543a51b3441e765f6702323c4e5de
     * @param id 内容id
     * @param timestamp 时间戳
     * @param ip ip取出点,如:10.73.136.168 => 1073136168
     * @param sign 签名字符串
     * @return failed | success
     * @throws Exception
     */
    @RequestMapping("push/{id}/{timestamp}/{ip}/{sign}")
    @ResponseBody
    @Profiled(tag="pushMsg")
    public String pushMsg(@PathVariable("id") int id,
                          @PathVariable("timestamp") int timestamp,
                          @PathVariable("ip") String ip,
                          @PathVariable("sign") String sign,
                          HttpServletRequest request) throws Exception{

        if (id!=0){

            StringBuffer signSign = new StringBuffer();
            signSign.append(id).append(timestamp).append(ip).append(Constants.API_SERCRET);

            String mySign = Md5Util.encode(signSign.toString());
            if (!mySign.equals(sign)){

                logger.info("非法{} {} {} {}|{}请求接口",id,timestamp,ip,sign,mySign);
                return "failed";
            }

            String requestIp = Util.getIpAddr(request);
            logger.info("{} 请求接口",requestIp);
            if (!requestIp.matches("^10.*")) {

                logger.info("非法{}请求接口",requestIp);
                return "failed";
            }
//            Sources sources = sourcesService.get(id);
//            String msg = Util.toDbColumn(sources);
            //ListenableFuture<SendResult<Integer, String>> result = kafkaTemplate.sendDefault(msg);

            return "success";
        }

        return "failed";
    }
}
